﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using KC.DataAccess.MV;

namespace KC.Presentation.Mv8CMS
{
	public partial class GalleryManager : Form
	{
		public GalleryManager()
		{
			InitializeComponent();
		}

		private void GalleryManager_Load(object sender, EventArgs e)
		{
			pictureBox1.AllowDrop = true;
			BuildTree();
			tvGallery.SelectedNode = tvGallery.Nodes[0];
		}

		private void BuildTree()
		{
			tvGallery.Nodes.Clear();
			TreeNode tn = new TreeNode();
			tn.Text = "/";
			tn.Tag = 0;
			tn.Nodes.AddRange(BuildTree(tn).ToArray());
			tvGallery.Nodes.Clear();
			tvGallery.Nodes.Add(tn);
			tvGallery.ExpandAll();
		}
		private List<TreeNode> BuildTree(TreeNode tn)
		{
			List<TreeNode> nodes = new List<TreeNode>();
			MV8DataContext dc = new MV8DataContext(System.Configuration.ConfigurationManager.ConnectionStrings["MV8"].ConnectionString);
			foreach (Gallery gal in from g in dc.Galleries where g.ParentId == (int)tn.Tag select g) {
				TreeNode tn2 = new TreeNode() { Text = gal.DisplayName, Tag = gal.id, ToolTipText = "GalleryId: " + gal.id.ToString() + "\nFilename: " + gal.Filename };
				tn2.Nodes.AddRange(BuildTree(tn2).ToArray());
				nodes.Add(tn2); }
			return nodes;
			

		}

		private void tvGallery_AfterSelect(object sender, TreeViewEventArgs e)
		{
			if (e.Node.Text == "/") {
				pbGallery.Image = null;
				pbThumb.Image = null;
				return; }
			MV8DataContext dc = new MV8DataContext(System.Configuration.ConfigurationManager.ConnectionStrings["MV8"].ConnectionString);
			Gallery gal = (from g in dc.Galleries where g.id == (int)e.Node.Tag select g).First();
			if (string.IsNullOrEmpty(gal.Filename) || gal.Filename.Length == 0) return;
			pbGallery.ImageLocation = gal.Filename;
			pbThumb.ImageLocation = gal.ThumbnailFilename;
		}

		private void tvGallery_ItemDrag(object sender, ItemDragEventArgs e)
		{
			DoDragDrop(e.Item, DragDropEffects.Move);
		}
		private void tvGallery_DragEnter(object sender, DragEventArgs e)
		{
			e.Effect = DragDropEffects.Move;
		}
		private void tvGallery_DragDrop(object sender, DragEventArgs e)
		{
			MV8DataContext dc = new MV8DataContext(System.Configuration.ConfigurationManager.ConnectionStrings["MV8"].ConnectionString);

			// Handle drops from other TreeNodes
			if (e.Data.GetDataPresent(typeof(TreeNode))) {

				// Update the TreeView
				TreeNode
					DestinationNode = tvGallery.GetNodeAt(tvGallery.PointToClient(new Point(e.X, e.Y))),
					newnode = (TreeNode)e.Data.GetData(typeof(TreeNode));
				DestinationNode.Nodes.Add((TreeNode)newnode.Clone());
				DestinationNode.Expand();
				int GalleryId = (int)newnode.Tag;
				newnode.Remove();

				// Update the Gallery
				Gallery gal = (from g in dc.Galleries
							   where g.id == GalleryId
							   select g).First();
				gal.ParentId = (int)DestinationNode.Tag;
				dc.SubmitChanges(); }

			// Handle drops from filesystem
			if (e.Data.GetDataPresent(DataFormats.FileDrop, false)) {
				string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

				// Update the TreeView and gallery in unison
				TreeNode DestinationNode = tvGallery.GetNodeAt(tvGallery.PointToClient(new Point(e.X, e.Y)));
				foreach (string file in files) {
					// TODO: Move the file to the right place (per gallery settings)

					// Create Thumbnail
					string ThumbFile = Path.GetDirectoryName(file) + "\\" + Path.GetFileNameWithoutExtension(file) + "_sm" + Path.GetExtension(file);
					if (!File.Exists(ThumbFile))
						try {
							KC.Business.Graphics.Management.CreateThumbnail(
								file,
								ThumbFile,
								int.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultThumbnailWidth"])); }
						catch (OutOfMemoryException) {
							MessageBox.Show("I ran out of memory in my tiny little thread apartment. Please generate this one manually.\n\n"+file);
							return;
						}

					// Collect stats for Gallery details
					GalleryPoker poker = new GalleryPoker(file);
					if (poker.ShowDialog() != System.Windows.Forms.DialogResult.OK) continue;

					// Create Gallery object
					Gallery gal = new Gallery();
					gal.Description = poker.Description;
					gal.DisplayName = poker.DisplayName;
					gal.Filename = file;
					gal.ThumbnailFilename = ThumbFile;
					gal.ParentId = (int)DestinationNode.Tag;
					if (poker.img != null) {
						gal.Width = poker.img.Width;
						gal.Height = poker.img.Height; }
					else {
						gal.Width = -1;
						gal.Height = -1; }
					gal.isDeepZoom = false;
					dc.Galleries.InsertOnSubmit(gal);
					dc.SubmitChanges();

					poker.img.Dispose();
					poker.Dispose();

					// Add new TreeNode
					DestinationNode.Nodes.Add(new TreeNode() { Text = gal.DisplayName, Tag = gal.id, ToolTipText = "GalleryId " + gal.id.ToString() + "\nFilename: " + gal.Filename });
					DestinationNode.Expand();
				}
			}
			BuildTree();
		}

		private void GalleryManager_ResizeEnd(object sender, EventArgs e)
		{
			UpdateSizes();
		}
		private void UpdateSizes()
		{
			pbGallery.Width = splitContainer1.Panel2.Width / 2;
			pbThumb.Width = pbGallery.Width;
		}

		private void pictureBox1_Click(object sender, EventArgs e)
		{
			if (MessageBox.Show("Hey, dumbass!\n\nReally delete this whole node?", "Really delete?", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
				return;

			// Delete the Gallery object
			MV8DataContext dc = new MV8DataContext(System.Configuration.ConfigurationManager.ConnectionStrings["MV8"].ConnectionString);
			TreeNode tn = tvGallery.SelectedNode;
			Gallery gal = (from g in dc.Galleries
						   where g.id == (int)tn.Tag
						   select g).First();
			dc.Galleries.DeleteOnSubmit(gal);
			dc.SubmitChanges();

			// Update the TreeView
			tn.Remove();
		}


	}
}
